package com.blazemina.socket 
{
	import flash.events.*;
	import flash.net.Socket;
	import flash.utils.ByteArray;

	/**
	 * ...
	 * @author JackChu
	 */
	public class SocketService extends Socket {
	
		private var response:String;
		
		private var msgLength:int;
		
		private var readBuffer:ByteArray;

		public function SocketService(host:String = null, port:uint = 0) {
			super(host, port);
			readBuffer = new ByteArray();
			configureListeners();
		}

		private function configureListeners():void {
			addEventListener(Event.CLOSE, closeHandler);
			addEventListener(Event.CONNECT, connectHandler);
			addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
		}
		
		private function closeHandler(e:Event):void {
			
		}
		
		private function connectHandler(e:Event):void {
			trace("connect success!");
		}
		
		private function ioErrorHandler(e:Event):void {
			
		}
		
		private function securityErrorHandler(e:Event):void {
			trace("securityErrorHandler");
		}
		
		
		/**
		 * 发送数据
		 * @param	cmd
		 * @param	data
		 */
		public function sendData(cmd:String, data:*):void {
			var sendData:ByteArray = new ByteArray();
			sendData.writeObject([cmd, data]);
			
			writeInt(sendData.length);
			writeBytes(sendData);
			flush();
		}
		
		private function socketDataHandler(e:ProgressEvent):void {
			while (connected) {
				if (this.bytesAvailable < 4) {
					return;
				} else {
					this.msgLength = this.readInt();
				}
				
				if (msgLength > 0 ) {
					readBuffer.position = 0;
					readBuffer.length = 0;
					this.readBytes(readBuffer, 0, msgLength);
					msgLength = 0;
					decode(readBuffer);
				} else {
					return;
				}
			}
		}
		
		public function decode(ba:ByteArray):void {
			var receiveData:Array = ba.readObject() as Array;
			if (data) {
				var cmd:String = receiveData[0];
				var data:Object = receiveData[1];
				trace("receive data,cmd:"+cmd+" data:"+data);
			}
		}

	}
}